/*
 * @Author: wangze@linkstec.com
 * @Date: 2022-01-17 09:52:08
 * @Function: Please Input Function
 */
// import moment from 'moment';
import numeral from 'numeral';

const commonUtil = {
  /**
   * 将{ a: 1, b: 2 } => a=1&b=2
   * @param {object} query
   */
   queryToString (query = {}) {
    const encode = encodeURIComponent;
    return Object.keys(query).map(
      key => (`${encode(key)}=${encode(query[key])}`)
    ).join('&');
  },

  /**
   * array 转换成 tree
   * @param {*} list
   * @param {*} id
   * @param {*} pid
   * @param {*} children
   */
   transToTree (list = [], id = 'id', pid = 'pid', children = 'children') {
    const data = JSON.parse(JSON.stringify(list));
    const result = [];
    if (!Array.isArray(data)) {
      return result;
    }
    data.forEach(item => {
      delete item[children];
    });
    const map = {};
    data.forEach(item => {
      const thisItem = item;
      for (const i in thisItem) {
        thisItem[i] = typeof thisItem[i] !== 'number' ? thisItem[i] : thisItem[i] + '';
      }
      map[item[id]] = thisItem;
    });
    data.forEach(item => {
      const parent = map[item[pid]];
      if (parent) {
        (parent[children] || (parent[children] = [])).push(item);
      } else {
        result.push(item);
      }
    });
    return result;
  },

  /**
   * 过滤treeData
   * @param {*} tree 需要过滤的树
   * @param {*} func 过滤规则 返回true则保留 返回false则过滤
   * @param {*} childrenKey 树的子级列表key
   * @returns 过滤后的树
   */
   treeFilter (tree, func, childrenKey) {
    // 使用map复制一下节点，避免修改到原树
    return tree.map(node => ({ ...node })).filter(node => {
      node[childrenKey] = node[childrenKey] && this.treeFilter(node[childrenKey], func, childrenKey);
      return func(node) || (node[childrenKey] && node[childrenKey].length);
    });
  },

  /**
   * 遍历treeData
   * @param {*} tree 需要遍历的树
   * @param {*} func 遍历到当前节点需要做的操作
   * @param {*} childrenKey 树的子级列表key
   * @returns 过滤后的树
   */
  treeMap (tree, func, childrenKey) {
    return tree.map(node => ({ ...node })).map(node => {
      node[childrenKey] = node[childrenKey] && this.treeMap(node[childrenKey], func, childrenKey);
      return func(node) || node;
    });
  },

  /**
   * 格式化比例
   * @param {*} value
   * @param {*} fixedNum 需要保留的小数位
   * @param {*} flag 1:百分比  2:千分比  3:万分比
   * @param {*} needNumber 是否需要数值
   * @param {*} needUnit 是否需要单位
   */
   formatRatio (value, fixedNum = 2, flag = 1, needNumber = true, needUnit = true) {
    let num = 0;
    if (!value) {
      value = 0;
    }
    num = numeral(value).value();

    let formatString = fixedNum > 0 ? '0,0.' : '0,0';
    for (let i = 0; i < fixedNum; i++) {
      formatString += '0';
    }

    if (flag === 1) { // 百分比
      return (needNumber ? numeral(num).multiply(100).format(formatString) : '') + (needUnit ? '%' : '');
    } else if (flag === 2) { // 千分比
      return (needNumber ? numeral(num).multiply(1000).format(formatString) : '') + (needUnit ? '‰' : '');
    } else if (flag === 3) { // 万分比
      return (needNumber ? numeral(num).multiply(10000).format(formatString) : '') + (needUnit ? '‱' : '');
    }
  },
  /**
   * 数字金额转中文金额
   * @param {string|number} money - 数字金额
   * @param {Boolean} isSimple - 是否中文小写
   * @returns
   */
  changeNumMoneyToChinese (money, isSimple) {
    const nums = [
      ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'],
      ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
    ];
    const intRadice = [
      ['', '十', '百', '千'],
      ['', '拾', '佰', '仟']
    ];
    var cnNums = isSimple ? nums[0] : nums[1]; // 汉字的数字
    var cnIntRadice = isSimple ? intRadice[0] : intRadice[1]; // 基本单位
    var cnIntUnits = ['', '万', '亿', '兆']; // 对应整数部分扩展单位
    var cnDecUnits = ['角', '分', '厘', '毫', '丝', '忽', '微丝', '微忽']; // 对应小数部分单位
    var cnInteger = '整'; // 整数金额时后面跟的字符
    var cnIntLast = '元'; // 整型完以后的单位
    var maxNum = 999999999999999.9999; // 最大处理的数字
    var IntegerNum; // 金额整数部分
    var DecimalNum; // 金额小数部分
    var ChineseStr = ''; // 输出的中文金额字符串
    var parts; // 分离金额后用的数组，预定义
    var Symbol = '';// 正负值标记

    if (money === '' && isSimple) return '';

    money = parseFloat(money);
    if (money >= maxNum) {
        return '超出最大处理数字';
    }
    if (money < 0) {
        money = -money;
        Symbol = '负 ';
    }
    money = money.toString(); // 转换为字符串
    if (money.indexOf('.') === -1) {
        IntegerNum = money;
        DecimalNum = '';
    } else {
        parts = money.split('.');
        IntegerNum = parts[0];
        DecimalNum = parts[1].substr(0, 8); // 最多取小数点后八位
    }
    if (parseInt(IntegerNum, 10) > 0) { // 获取整型部分转换
        var zeroCount = 0;
        var IntLen = IntegerNum.length;
        for (var i = 0; i < IntLen; i++) {
            var n = IntegerNum.substr(i, 1);
            var p = IntLen - i - 1;
            var q = p / 4;
            var m = p % 4;
            if (n === '0') {
                zeroCount++;
            } else {
                if (zeroCount > 0) {
                    ChineseStr += cnNums[0];
                }
                zeroCount = 0; // 归零
                ChineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
            }
            if (m === 0 && zeroCount < 4) {
                ChineseStr += cnIntUnits[q];
            }
        }
        if (!isSimple) {
          ChineseStr += cnIntLast;
        }
        // 整型部分处理完毕
    }
    if (DecimalNum !== '') { // 小数部分
      var decLen = DecimalNum.length;
      if (isSimple) {
        if (ChineseStr.length === 0) {
          ChineseStr += '零';
        }
        ChineseStr += '点';
      }
      for (let i = 0; i < decLen; i++) {
        const n = DecimalNum.substr(i, 1);
        if (isSimple) {
          ChineseStr += cnNums[Number(n)];
        } else {
          if (n !== '0') {
            ChineseStr += cnNums[Number(n)] + cnDecUnits[i];
          }
        }
      }
    }
    if (ChineseStr === '' && !isSimple) {
        ChineseStr += cnNums[0] + cnIntLast + cnInteger;
    } else if (DecimalNum === '' && !isSimple) {
        ChineseStr += cnInteger;
    }
    ChineseStr = Symbol + ChineseStr;

    return ChineseStr;
  },
  /**
   * 格式化大数据
   * @param {*} value
   * @param {*} fixedNum 需要保留的小数位
   * @param {*} isInt 是否为整数型
   * @param {*} needNumber 是否需要数值
   * @param {*} needUnit 是否需要单位
   */
  formatBigNumber (value, fixedNum = 2, isInt = false, needNumber = true, needUnit = true) {
    let num = 0;
    if (!value) {
      value = 0;
    }
    num = numeral(value).value();
    const abs = Math.abs(num);// 取绝对值

    let formatString = fixedNum > 0 ? '0,0.' : '0,0';
    for (let i = 0; i < fixedNum; i++) {
      formatString += '0';
    }

    const hundredMillion = 100000000; // 亿
    const tenMillion = 10000000; // 千万
    const million = 1000000; // 百万
    const tenThousand = 10000; // 万

    if (abs >= hundredMillion) { // 亿
      return (needNumber ? numeral(value).divide(hundredMillion).format(formatString) : '') + (needUnit ? '亿' : '');
    } else if (abs >= tenMillion) { // 千万
      return (needNumber ? numeral(value).divide(tenMillion).format(formatString) : '') + (needUnit ? '千万' : '');
    } else if (abs >= million) { // 百万
      return (needNumber ? numeral(value).divide(million).format(formatString) : '') + (needUnit ? '百万' : '');
    } else if (abs >= tenThousand) { // 万
      return (needNumber ? numeral(value).divide(tenThousand).format(formatString) : '') + (needUnit ? '万' : '');
    } else { // 万以下
      if (isInt) {
        return (needNumber ? numeral(value).format('0,0') : '') + (needUnit ? '' : '');
      } else {
        return (needNumber ? numeral(value).format(formatString) : '') + (needUnit ? '' : '');
      }
    }
  },

  /**
   * 获取cookie
   * @param {*} cName
   */
  getCookie (cName) {
    if (document.cookie.length > 0) {
      let cStart = document.cookie.indexOf(cName + '=');
      if (cStart !== -1) {
        cStart = cStart + cName.length + 1;
        let cEnd = document.cookie.indexOf(';', cStart);
        if (cEnd === -1) cEnd = document.cookie.length;
        return unescape(document.cookie.substring(cStart, cEnd));
      }
    }
    return '';
  },

  /**
   * 检查是否是货币类型
   * @param {*} type
   * @returns
   */
  checkIsMonetaryFund (type, feild) {
    if (!type) {
      return false;
    }
    type = type + '';
    if (feild === 'type_code') {
      if (type === '4') {
        return true;
      }
      return false;
    } else {
      if (type === '3') {
        return true;
      }
      return false;
    }
  },

  /**
   * 检查选择的账号、输入的金额
   * @param {*} param0
   */
  checkAccountAmount ({ account, amount, balance }) {
    // 校验账号选择
    if (!account) {
      return { message: '请选择交易账户', success: false };
    }
    // 校验金额填写
    if (amount.length < 10) {
      return { message: '总投金额请输入完整，位数不足用0补齐', success: false };
    }
    // 校验金额填写
    if (numeral(amount).value() === 0) {
      return { message: '请输入总投金额', success: false };
    }
    // 校验金额填写 < 可用资金
    if (numeral(amount).subtract(balance).value() > 0) {
      return { message: '余额不足，请确认可用资金余额', success: false };
    }
    return { success: true };
  },
  // 数组偏平化
  flatArray (arr) {
    let result = [];
    for (var i = 0; i < arr.length; i++) {
      if (Array.isArray(arr[i])) {
        result = result.concat(commonUtil.flatArray(arr[i]));
      } else {
        result.push(arr[i]);
      }
    }
    return result;
  },
  /**
   * 时间戳转时间格式
   * type 1 为日期 2为时间
   */
  getTime (value, type = 1, connector = '-') {
    const now = new Date(value);
    const year = now.getFullYear();
    let month = now.getMonth() + 1;
    let date = now.getDate();
    month = month < 10 ? '0' + month : month;
    date = date < 10 ? '0' + date : date;
    let hour = now.getHours();
    let minute = now.getMinutes();
    let second = now.getSeconds();
    hour = hour < 10 ? '0' + hour : hour;
    minute = minute < 10 ? '0' + minute : minute;
    second = second < 10 ? '0' + second : second;
    if (type === 1) {
      return year + connector + month + connector + date;
    } else {
      return year + connector + month + connector + date + ' ' + hour + ':' + minute + ':' + second;
    }
  }
};

export default commonUtil;
